import {
    getInformationDetails,
    getPaid,
    getSalaryAli,
} from '../../api/get-paid.js'
import {
    getUrgentInfo,
    bindAlipayAccountApi,
    getAlipaySchemeApi,
} from '../../api/app'
import {
    getContractList
} from '../../api/contract.js'
import dayjs from 'dayjs'
import {
    openSalaryCard,
    querySalaryCard
} from '../../utils/salary-card'
import user from '../../utils/user.js'
import {
    bindAlipayAccount
} from '../../api/salary-card'
import {
    anit,
    confirm,
    goApp,
    goToContract,
    getCardAge,
    reportEvent,
    toast,
    wait,
} from '../../utils/util'
const app = getApp()
Page({
    data: {
        aaa: '',
        isTipUp: false,
        copyData: '',
        alipayCode: '',
        flag: false,
        showDialog: false,
        isUp: false,
        getPaid: false, // 判断有没有领取薪资成功
        companyId: '',
        detailsList: {},
        id: '',
        contractList: [],
        checked: true,
        isOpenSalaryCard: false,
        isEdition: false,
        bankcard: '',
        idCardFront: '',
        isCollectOpenBankAddress: '0',
        isshowCollectOpenBankAddress: 0,
        isCollectOpenBankName: '0',
        isCollectOpenBankCity: '0',
        isCollectBankCardImg: '0',
    },
    async onLoad(option) {
        console.log(option, 'option')
        this.setData({
            isCollectOpenBankAddress: option.isCollectOpenBankAddress,
            isCollectOpenBankName: option.isCollectOpenBankName,
            isCollectOpenBankCity: option.isCollectOpenBankCity,
            isCollectBankCardImg: option.isCollectBankCardImg,
        })
        await user.waitLogin()
        this.setData({
            id: option.id,
            isOpenSalaryCard: user.isOpenSalaryCard,
        })
        const result = await getInformationDetails({
            id: option.id,
        })

        console.log(666666, result)
        if (result.params.sign_time_in) {
            result.params.sign_time_in = result.params.sign_time_in.split(
                ' '
            )[1]
        }
        if (result.params.sign_time_out) {
            result.params.sign_time_out = result.params.sign_time_out.split(
                ' '
            )[1]
        }
        //
        const age = await getCardAge(result.idCardNo)
        console.log(age, 'age')
        if (result.flagQuicklyGetSalary && age >= 45) {
            this.setData({
                isEdition: true,
            })
        }
        console.log(this.data.isEdition, 'isEdition')
        this.setData({
            detailsList: result,
            companyId: result.companyId,
        })
        // 分割时间
        this.setData({
            ['detailsList.paydayTime']: this.data.detailsList.payTime.split(
                /[ ]+/
            )[0],
        })
        console.log(5555, this.data.detailsList)
        const contractList = await getContractList({
            companyId: result.companyId,
        })
        this.data.contractList = contractList
        if (contractList.length === 0) {
            return
        }
        this.data.hasContract = true
        console.log('第一个合同')
        app.confirm(
            `应劳务公司要求，需要您签署合同后领薪，您有${contractList.length}份合同待签署。`
        ).then(() => {
            goToContract(contractList[0].flowPath, contractList[0].id)
        })
    },
    onCloseTip() {
        this.setData({
            isTipUp: false
        })
    },
    isAfter2024Dec1(date) {
        const targetDate = dayjs('2024-12-01')
        const inputDate = dayjs(date)
        return inputDate.isAfter(targetDate) || inputDate.isSame(targetDate)
    },
    onToAlipayRedBagRule() {
        wx.downloadFile({
            url: 'https://bullet-static.oss-cn-shanghai.aliyuncs.com/paywage-file/12%E6%9C%88%E6%94%AF%E4%BB%98%E5%AE%9D%E6%8F%90%E7%8E%B0%E5%8F%B0%E6%B4%BB%E5%8A%A8%E8%A7%84%E5%88%99.docx',
            success: (res) => {
                console.log(res)
                wx.openDocument({
                    filePath: res.tempFilePath,
                    fileType: 'docx',
                    showMenu: true, // 是否显示右上角菜单按钮 默认为false(看自身需求，可要可不要。后期涉及到右上角分享功能)
                })
            }
        })
        // wx.navigateTo({
        //     url: '/pages/alipay-red-packet-rule/alipay-red-packet-rule',
        // })
    },
    async onShow() {
        if (this.data.hasContract === true) {
            const result = await getContractList({
                companyId: this.data.companyId,
            })
            this.data.contractList = result
            if (result.length === 0) {
                return
            }
            console.log('第2个合同')
            await app.confirm(
                `应劳务公司要求，需要您签署合同后领薪，您有${result.length}份合同待签署。`
            )
            goToContract(result[0].flowPath, result[0].id)
        }
        if (this.isAfter2024Dec1(dayjs().format('YYYY-MM-DD'))) {
            this.setData({
                isTipUp: true
            })
        } else {
            this.setData({
                isTipUp: false
            })
        }
        await this.getUrgentInfo()
        this.setData({
            bankcard: user.bankCardNo,
        })
    },
    // 获取个人信息
    async getUrgentInfo() {
        const result = await getUrgentInfo()
        console.log(result, 'resres')
        this.data.idCardFront = result.idCardFront
    },
    onLook() {
        wx.navigateTo({
            url: '/pages/alipay-desc/alipay-desc',
        })
    },
    onSureSubmit() {
        if (!this.data.alipayCode) {
            wx.showToast({
                title: '请输支付宝账号',
                icon: 'none',
            })
        } else {
            bindAlipayAccount({
                alipayAccount: this.data.alipayCode,
            }).then(() => {
                wx.showToast({
                    title: '绑定成功',
                    icon: 'none',
                })
                user.reLogin()
                this.setData({
                    flag: true,
                    isUp: false,
                })
            })
        }
    },
    // 点击复制
    // onCopywxtap() {
    //     wx.setClipboardData({
    //         data: this.data.copyData,
    //         success: function () {
    //             wx.getClipboardData({
    //                 success: function (res) {
    //                     console.log(res.data) // 打印赋值的数据
    //                     wx.showToast({
    //                         title: '复制成功',
    //                         icon: 'none'
    //                     })
    //                     wx.navigateTo({
    //                         url: '/pages/alipayWebView/alipayWebView',
    //                     })
    //                 }
    //             })
    //         }
    //     })
    // },

    onOpaenDialog() {
        this.setData({
            showDialog: true,
        })
    },
    onClosedialog() {
        this.setData({
            showDialog: false,
        })
    },
    async toBank() {
        await wx.navigateTo({
            url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectBankCardImg=${this.data.isCollectBankCardImg}&from=salary`,
        })
    },

    async onGetBankInAlipay() {
        anit(async () => {
            if (!user.alipayOpenId & !user.alipayAccount) {
                this.setData({
                    flag: true,
                    isUp: true,
                })
                return
            }
            if (this.data.detailsList.isShowPop) {
                await app.alert('应劳务公司要求，需要您填写完银行卡号码。')
                await this.toBank()
                return
            }
            if (
                this.data.isCollectOpenBankName === '1' &&
                !user.hasOpenBankInfo
            ) {
                await app.alert('应劳务公司要求，需要您填写完开户行城市信息。')
                await this.toBank()
                return
            }
            if (
                this.data.detailsList.params.isNeedIdcardPhoto === 1 &&
                !user.hasCardPhoto
            ) {
                await app.alert('未上传身份证照片，请在上传后在进行领取。')
                wx.navigateTo({
                    url: '/pages/card-info/card-info',
                })
                return
            }

            await getSalaryAli({
                id: this.data.detailsList.id,
                phone: user.phoneNum,
                detailOrderNo: this.data.detailsList.detailOrderNo,
            }).catch(async (err) => {
                const event = await goApp(
                    'applet::/pages/job-status/job-status?title=提现失败&content=' +
                    (err?.data?.msg ?? '网络错误，请稍后再试') +
                    '&type=warn&color=#FF7E68&id=' +
                    this.data.companyId +
                    '&phone=' +
                    this.data.detailsList.params.linkmanList[0].phone +
                    '&isfalse=true' +
                    '&frompay=' +
                    'true'
                )
                this.channelPhone(event)
                throw new Error('支付宝领薪失败')
            })
            await wait(100)
            const event = await goApp(
                'applet::/pages/job-status/job-status?title=处理中&content=' +
                '转账处理中，请稍后' +
                '&type=success&color=#04CD5A&id=' +
                this.data.companyId +
                '&order=' +
                this.data.detailsList.detailOrderNo +
                '&payid=' +
                this.data.id +
                '&phone=' +
                this.data.detailsList.params.linkmanList[0].phone +
                '&frompay=' +
                'true' +
                '&platform=' +
                'alipay'
            )
            this.channelPhone(event)
            return 0
            // if (!user.alipayAccount) {
            //     this.setData({
            //         flag: false
            //     })
            // } else {
            //     getAlipaySchemeApi({
            //         page: 'package-mine/pages/salary/salary',
            //         query: 'from=scheme'
            //     }).then((res) => {
            //         console.log(res)
            //         this.setData({
            //             copyData: res,
            //             flag: true
            //         })
            //     })
            // }
        })
    },
    onClosePop() {
        this.setData({
            isUp: false,
        })
    },
    async onGetBank() {
        console.log(
            this.data.isCollectBankCardImg,
            user.bankCardImg,
            'this.data.isCollectBankCardImgthis.data.isCollectBankCardImgthis.data.isCollectBankCardImg'
        )
        const res = await getInformationDetails({
            id: this.data.id,
        })
        console.log(res, this.data.contractList, 'gjidsghy')
        this.setData({
            isshowCollectOpenBankAddress: res.isCollectOpenBankAddress,
        })
        if (res.params.sign_time_in) {
            res.params.sign_time_in = res.params.sign_time_in.split(' ')[1]
        }
        if (res.params.sign_time_out) {
            res.params.sign_time_out = res.params.sign_time_out.split(' ')[1]
        }
        //
        const age = await getCardAge(res.idCardNo)
        console.log(age, 'age')
        if (res.flagQuicklyGetSalary && age >= 45) {
            this.setData({
                isEdition: true,
            })
        }
        this.setData({
            detailsList: res,
            companyId: res.companyId,
        })
        // const obj = await openSalaryCard(this.data.companyId,user.userName, user.cardNo)
        let bankcardflag = !!this.data.bankcard
        let idCardFront = !!this.data.idCardFront
        console.log(
            this.data.detailsList.params.isNeedIdcardPhoto,
            this.data.detailsList.isShowPop,
            idCardFront,
            bankcardflag,
            '查看状态'
        )
        console.log(999, this.data.detailsList, user)
        if (
            this.data.detailsList.params.isNeedIdcardPhoto == 1 &&
            this.data.detailsList.isShowPop == 1 &&
            !idCardFront
        ) {
            wx.navigateTo({
                url: `/pages/bank-id-card/bank-id-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=salary`,
            })
            return
        }
        if (this.data.detailsList.isShowPop) {
            await app.alert('应劳务公司要求，需要您填写完银行卡号码。')
            await wx.navigateTo({
                url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectBankCardImg=${this.data.isCollectBankCardImg}&from=salary`,
            })
            return
        }
        // b端勾选了开户行但是客户没有开户行信息
        if (this.data.isCollectOpenBankName === '1' && !user.hasOpenBankInfo) {
            await app.alert('应劳务公司要求，需要您填写完银行开户行信息。')
            await wx.navigateTo({
                url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=salary`,
            })
            return
        }
        // b端勾选了开户城市但是客户没有开户城市
        if (this.data.isCollectOpenBankCity === '1' && !user.hasOpenBankCity) {
            await app.alert('应劳务公司要求，需要您填写完开户行城市信息。')
            await wx.navigateTo({
                url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectBankCardImg=${this.data.isCollectBankCardImg}&from=salary`,
            })
            return
        }
        if (this.data.isCollectBankCardImg === '1' && !user.bankCardImg) {
            await app.alert('应劳务公司要求，需要您提交银行卡照片。')
            await wx.navigateTo({
                url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectBankCardImg=${this.data.isCollectBankCardImg}&from=salary`,
            })
            return
        }
        // if (this.data.isshowCollectOpenBankAddress === 1) {
        //     await app.alert(`应劳务公司要求，需要您填写完银行卡号码和银行卡开户行。`)
        //     await wx.navigateTo({
        //       url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}`,
        //     })
        //     return
        // }
        const isSalary = wx.getStorageSync('isSalary')
        // 上报统计45岁点击提现到银行卡 次数
        if (!isSalary) {
            reportEvent('salary_card', {
                userid: user.userId,
                age: getCardAge(this.data.detailsList.idCardNo),
                salary_channel: '银行卡',
            })
            wx.setStorageSync('isSalary', 'true')
        }
        // console.log(this.data.detailsList.params.isNeedIdcardPhoto, !!this.data.idCardFront, !user.hasCardPhoto)
        // 查询微工卡
        let result
        try {
            result = await querySalaryCard(this.data.companyId)
        } catch (err) {
            if (err) {
                openSalaryCard(this.data.companyId)
            } else {
                app.alert('劳务公司暂未开通微工卡服务')
            }
        }
        if (!result.isOpenSalaryCard) {
            app.alert('劳务公司暂未开通微工卡服务')
            return
        }
        if (this.data.contractList.length === 0) {
            this.getPaid(1)
            return
        }
        console.log('第3个合同')
        await app.alert(
            `应劳务公司要求，需要您签署合同后领薪，您有${this.data.contractList.length}份合同待签署。`
        )
        goToContract(
            this.data.contractList[0].flowPath,
            this.data.contractList[0].id
        )
    },
    async onGetWallet() {
        const res = await getInformationDetails({
            id: this.data.id,
        })
        this.setData({
            isshowCollectOpenBankAddress: res.isCollectOpenBankAddress,
        })
        if (this.data.contractList.length === 0) {
            // 上报统计45岁点击提现到领钱 次数
            const isSalary = wx.getStorageSync('isSalary')
            if (!isSalary) {
                reportEvent('salary', {
                    userid: user.userId,
                    age: getCardAge(this.data.detailsList.idCardNo),
                    salary_channel: '零钱',
                })
                wx.setStorageSync('isSalary', 'true')
            }
            if (this.data.detailsList.isShowPop) {
                await app.alert('应劳务公司要求，需要您填写完银行卡号码。')
                await wx.navigateTo({
                    url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=salary`,
                })
                return
            }
            // b端勾选了开户行但是客户没有开户行信息
            if (
                this.data.isCollectOpenBankName === '1' &&
                !user.hasOpenBankInfo
            ) {
                await app.alert('应劳务公司要求，需要您填写完银行开户行信息。')
                await wx.navigateTo({
                    url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=salary`,
                })
                return
            }
            // b端勾选了开户城市但是客户没有开户城市
            if (
                this.data.isCollectOpenBankCity === '1' &&
                !user.hasOpenBankCity
            ) {
                await app.alert('应劳务公司要求，需要您填写完开户行城市信息。')
                await wx.navigateTo({
                    url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=salary`,
                })
                return
            }
            // if (this.data.isshowCollectOpenBankAddress === 1) {
            //     await app.alert(`应劳务公司要求，需要您填写完银行卡号码和银行卡开户行。`)
            //     await wx.navigateTo({
            //       url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}`,
            //     })
            //     return
            // }
            this.getPaid(0)
            return
        }
        console.log('第4个合同')
        await app.alert(
            `应劳务公司要求，需要您签署合同后领薪，您有${this.data.contractList.length}份合同待签署。`
        )
        goToContract(
            this.data.contractList[0].flowPath,
            this.data.contractList[0].id
        )
    },
    async getPaid(isBank) {
        // !!this.data.idCardFront
        if (
            this.data.detailsList.params.isNeedIdcardPhoto == 1 &&
            !user.hasCardPhoto
        ) {
            await confirm('未上传身份证照片，请在上传后在进行领取')
            // 身份证上传1
            // /pages/basic-form/basic-form?isEdit=1
            //
            wx.navigateTo({
                url: '/pages/card-info/card-info',
            })
        } else {
            anit(async () => {
                // BANK_ACCOUNT
                try {
                    const result = await getPaid({
                        id: this.data.id,
                        detailOrderNo: this.data.detailsList.detailOrderNo,
                        transferScene: isBank ?
                            'BANK_ACCOUNT' : 'WECHATPAY_ACCOUNT',
                    }, {
                        isToast: false,
                    })

                    if (result && result.type === '转账失败') {
                        const event = await goApp(
                            'applet::/pages/job-status/job-status?title=提现失败&content=' +
                            result.msg +
                            '&type=warn&color=#FF7E68&id=' +
                            this.data.companyId +
                            '&phone=' +
                            this.data.detailsList.params.linkmanList[0]
                                .phone +
                            '&order=' +
                            this.data.detailsList.detailOrderNo +
                            '&payid=' +
                            this.data.id +
                            '&frompay=' +
                            'true'
                        )
                        this.channelPhone(event)
                        return 0
                    } else if (result && result.msg) {
                        const event = await goApp(
                            'applet::/pages/job-status/job-status?title=提现成功&content=' +
                            result.msg +
                            '&type=success&color=#04CD5A&id=' +
                            this.data.companyId +
                            '&order=' +
                            this.data.detailsList.detailOrderNo +
                            '&payid=' +
                            this.data.id +
                            '&phone=' +
                            this.data.detailsList.params.linkmanList[0]
                                .phone +
                            '&frompay=' +
                            'true'
                        )
                        this.channelPhone(event)
                        return 0
                    }
                    const event = await goApp(
                        'applet::/pages/job-status/job-status?title=提现成功&content=您已完成提现，稍后查看微信转账通知&type=success&color=#04CD5A&id=' +
                        this.data.companyId +
                        '&order=' +
                        this.data.detailsList.detailOrderNo +
                        '&payid=' +
                        this.data.id +
                        '&phone=' +
                        this.data.detailsList.params.linkmanList[0].phone +
                        '&frompay=' +
                        'true'
                    )
                    this.channelPhone(event)
                } catch (err) {
                    console.log(err, 'resultresult')
                    const event = await goApp(
                        'applet::/pages/job-status/job-status?title=提现失败&content=' +
                        (err?.data?.msg ?? '网络错误，请稍后再试') +
                        '&type=warn&color=#FF7E68&id=' +
                        this.data.companyId +
                        '&phone=' +
                        this.data.detailsList.params.linkmanList[0].phone +
                        '&isfalse=true' +
                        '&frompay=' +
                        'true'
                    )
                    this.channelPhone(event)
                }
            }, 300)
        }
    },
    channelPhone(event) {
        event.eventChannel.emit(
            'phone',
            this.data.detailsList?.params?.linkmanList ?? []
        )
    },
    // 联系驻厂
    async contactResident() {
        const linkmanList = this.data.detailsList?.params?.linkmanList ?? []
        const sheet = linkmanList.map((item) => {
            return item.linkman + ' ' + item.phone
        })
        const result = await wx.showActionSheet({
            itemList: sheet,
        })
        wx.makePhoneCall({
            phoneNumber: linkmanList[result.tapIndex].phone,
        })
    },
    onChecked() {
        this.setData({
            checked: !this.data.checked,
        })
    },
})